﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Timers;

namespace WindowsFormsApplication1
{
    public class ClientSocketData
    {
        public Delegate closeSocketFunction;

        public SocketController socket;
        public byte[] dataBuffer = new byte[1024];
        public int UserID = 0;

        //This timer is used to drop the connection if a login attempt is not made within 5 seconds
        private Timer timerLoginTimout = new Timer(5000);

        private Timer dropConnectionTimer = new Timer(1000 * 15);

        public string clientID = "";
        public bool isGM = false;

        public ClientSocketData(Socket clientSocket)
        {
            if (clientSocket != null)
            {
                _clientIP = clientSocket.RemoteEndPoint.ToString();
                _clientIP = _clientIP.Substring(0, _clientIP.IndexOf(':'));

                clientSocket.SendTimeout = 1000 * 10;
                socket = new SocketController(clientSocket, this);

                timerLoginTimout.Elapsed += new ElapsedEventHandler(timerLoginTimout_Elapsed);
                timerLoginTimout.AutoReset = false;
                timerLoginTimout.Start();

                dropConnectionTimer.Elapsed += new ElapsedEventHandler(timerLoginTimout_Elapsed);
                dropConnectionTimer.AutoReset = true;
                dropConnectionTimer.Start();
            }
        }

        private string _clientIP = "";
        public string clientIP { get{ return _clientIP; }}

        public void killLoginTimout()
        {
            try
            {
                timerLoginTimout.Stop();
                timerLoginTimout.Dispose();
            }
            catch { }
        }
        public void killDropConnectionTimer()
        {
            try
            {
                dropConnectionTimer.Stop();
                dropConnectionTimer.Dispose();
            }
            catch { }
        }

        private void closeThisSocket()
        {
            closeSocketFunction.DynamicInvoke(this);
        }
        void timerLoginTimout_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (sender == timerLoginTimout)
            {
                closeThisSocket();
                return;
            }

            try
            {
                if (socket.Connected == false)
                {
                    closeThisSocket();
                    return;
                }
                socket.BeginSend("<keepalive />");
            }
            catch
            {
                closeThisSocket();
            }
        }

        
    }
}
